package com.sora.pipeline.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sora.pipeline.domain.User;
import com.sora.pipeline.domain.dto.RegisterRequest;
import com.sora.pipeline.domain.dto.UpdateProfileRequest;
import com.sora.pipeline.service.AuthService;
import com.sora.pipeline.service.UserService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class AuthServiceImpl implements AuthService {
    private final UserService userService;
    private final PasswordEncoder passwordEncoder;

    public AuthServiceImpl(UserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Map<String, Object> login(String username, String password, String captcha) {
        User user = userService.lambdaQuery().eq(User::getUsername, username).one();
        if (user == null) {
            return failure(1003, "用户不存在");
        }
        String stored = user.getPasswordHash();
        if (stored == null || !passwordEncoder.matches(password, stored)) {
            return failure(1001, "用户名或密码错误");
        }
        Map<String, Object> data = new HashMap<>();
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("name", user.getName());
        userInfo.put("role", "admin");
        userInfo.put("roleName", "系统管理员");
        userInfo.put("orgId", 1);
        userInfo.put("orgName", "石化园区A区管理中心");
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("permissions", new String[]{"dashboard", "inspection", "lines", "defects", "remedies", "statistics"});
        data.put("token", "mock-token");
        data.put("userInfo", userInfo);
        data.put("expiresIn", 1800);
        data.put("code", 0);
        data.put("message", "登录成功");
        return data;
    }

    @Override
    public Map<String, Object> register(RegisterRequest request) {
        // 检查用户名是否已存在
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, request.getUsername())
                   .eq(User::getDeleted, false);
        User existingUser = userService.getOne(queryWrapper);
        if (existingUser != null) {
            return failure(1004, "用户名已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        // 使用BCrypt加密密码
        user.setPasswordHash(passwordEncoder.encode(request.getPassword()));
        
        // 设置可选字段，没有数据的设为null
        user.setName(StringUtils.hasText(request.getUsername()) ? request.getUsername() : null);
        user.setEmail(null);
        user.setPhone(null);
        user.setAvatar(null); // 默认头像为null
        
        // 设置默认角色为普通用户（假设roleId=2为普通用户）
        user.setRoleId(2);
        
        // 设置状态为pending，需要审核
        user.setStatus("pending");
        
        // 设置时间戳
        LocalDateTime now = LocalDateTime.now();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);
        user.setDeleted(false);
        
        // 保存用户
        boolean success = userService.save(user);
        if (!success) {
            return failure(1005, "注册失败，请重试");
        }

        // 返回注册结果
        Map<String, Object> data = new HashMap<>();
        data.put("registrationId", user.getId());
        data.put("status", "pending");
        data.put("submitTime", now.toString());
        data.put("code", 0);
        data.put("message", "注册申请已提交，等待管理员审核");
        return data;
    }

    @Override
    public Map<String, Object> updateProfile(Long userId, UpdateProfileRequest request) {
        // 查找用户
        User user = userService.getById(userId);
        if (user == null) {
            return failure(1003, "用户不存在");
        }

        // 检查邮箱是否被其他用户使用
        if (StringUtils.hasText(request.getEmail())) {
            LambdaQueryWrapper<User> emailQuery = new LambdaQueryWrapper<>();
            emailQuery.eq(User::getEmail, request.getEmail())
                     .ne(User::getId, userId)
                     .eq(User::getDeleted, false);
            User existingUser = userService.getOne(emailQuery);
            if (existingUser != null) {
                return failure(1006, "邮箱已被其他用户使用");
            }
        }

        // 检查手机号是否被其他用户使用
        if (StringUtils.hasText(request.getPhone())) {
            LambdaQueryWrapper<User> phoneQuery = new LambdaQueryWrapper<>();
            phoneQuery.eq(User::getPhone, request.getPhone())
                     .ne(User::getId, userId)
                     .eq(User::getDeleted, false);
            User existingUser = userService.getOne(phoneQuery);
            if (existingUser != null) {
                return failure(1007, "手机号已被其他用户使用");
            }
        }

        // 更新用户信息
        user.setName(request.getName());
        user.setEmail(StringUtils.hasText(request.getEmail()) ? request.getEmail() : null);
        user.setPhone(StringUtils.hasText(request.getPhone()) ? request.getPhone() : null);
        user.setAvatar(StringUtils.hasText(request.getAvatar()) ? request.getAvatar() : null);
        user.setUpdatedAt(LocalDateTime.now());

        // 保存更新
        boolean success = userService.updateById(user);
        if (!success) {
            return failure(1008, "更新个人信息失败，请重试");
        }

        // 返回用户信息数据
        return buildUserInfo(user);
    }

    @Override
    public Map<String, Object> getUserProfile(Long userId) {
        User user = userService.getById(userId);
        if (user == null) {
            return failure(1003, "用户不存在");
        }

        // 返回用户信息数据
        return buildUserInfo(user);
    }

    /**
     * 构建用户信息对象
     */
    private Map<String, Object> buildUserInfo(User user) {
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("name", user.getName());
        userInfo.put("email", user.getEmail());
        userInfo.put("phone", user.getPhone());
        userInfo.put("avatar", user.getAvatar());
        userInfo.put("role", "admin"); // 暂时硬编码，后续可以从角色表获取
        userInfo.put("roleName", "系统管理员");
        userInfo.put("orgId", 1);
        userInfo.put("orgName", "石化园区A区管理中心");
        userInfo.put("status", user.getStatus());
        userInfo.put("lastLoginAt", user.getLastLogin());
        userInfo.put("createdAt", user.getCreatedAt());
        userInfo.put("updatedAt", user.getUpdatedAt());
        userInfo.put("permissions", new String[]{"dashboard", "inspection", "lines", "defects", "remedies", "statistics"});
        return userInfo;
    }

    private Map<String, Object> failure(int code, String message) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("message", message);
        map.put("data", null);
        return map;
    }
}


